前序Preorder: 先访问根节点,然后访问左子树,最后访问右子树。子树递归同理 中序Inorder: 先访问左子树,然后访问根节点,最后访问右子树. 后序Postorder:先访问左子树,然后访问右子树,最后访问根节点. classNode:def__init__(self,key):self.left=Noneself.right=Noneself.val=keydefprintInorder(root):ifroot...
*/classSolution{public List<Integer>preorderTraversal(TreeNode root){List<Integer>result=newLinkedList<>();TreeNode current=root;TreeNode prev=null;while(current!=null){if(current.left==null){result.add(current.val);current=current.right;}else{// has left, then find the rightmost of left su...
对于inorder来说,遍历的顺序就是node出现在笔触上方的顺序;对于preorder来说,遍历的顺序就是node出现在笔触右方的顺序;对于postorder来说,遍历的顺序就是node出现在笔触左边的顺序。 recursion方法 对于recursion来说,代码非常简单,基本就是定义的翻译,因此不做过多阐述,仅附上代码。 publicList<Integer>inorderTravers...
65publicstaticvoidinOrder(TreeNode root){66if(root ==null)return;67inOrder(root.left);68visit(root);69inOrder(root.right);70}7172publicstaticvoidinOrder2(TreeNode root){73if(root ==null)return;74Stack<TreeNode> stack =newStack<TreeNode>();75while(!stack.empty() || root !=null){76...
postorder tranverse:跟前序遍历比较像 迭代写法: classSolution{publicList<Integer>postorderTraversal(TreeNode root){ List<Integer> res =newArrayList<>();if(root ==null)returnres; LinkedList<TreeNode> stack =newLinkedList<>(); stack.push(root);while(!stack.isEmpty()){TreeNodecur=stack.pop();...
Traverse right preorder(root.right) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print("Inorder traversal ") inorder(root) print("\nPreorder traversal ") preorder(root) print("\nPostorder traversal ") postorder(...
tree traversal 分为四种。 void BinaryTree<T>::preOrder(TreeNode * cur) { if (cur != NULL) { yell(cur->data); // yell is some imaginary function preOrder(cur->left); preOrder(cur->right); } } void BinaryTree<T>::inOrder(TreeNode * cur) { ...
1 preorder: 节点入栈一次, 入栈之前访问。 2 inorder:节点入栈一次,出栈之后访问。 3 postorder:节点入栈2次,第二次出战后访问。 1classSolution {2public:3vector<int> preorderTraversal(TreeNode *root) {45vector<int>result;6stack<TreeNode*>stack;78TreeNode *p =root;910while( NULL != p ||...
Binary Tree Postorder Traversal 题目链接 题目要求: Given a binary tree, return thepostordertraversal of its nodes' values. For example: Given binary tree{1,#,2,3}, 1 \ 2 / 3 return[3,2,1]. Note: Recursive solution is trivial, could you do it iteratively?
Inorder 方法一:和Preorder方法一类似,直接做,但是需要一个计数器,第二次出栈的时候才可以输出。 classSolution {public: vector<int> inorderTraversal(TreeNode*root) { vector<int>res;if(root==NULL)returnres; unordered_map<TreeNode *,int> hash;//default value is 0;stack<TreeNode *>s({root})...