前序Preorder: 先访问根节点,然后访问左子树,最后访问右子树。子树递归同理 中序Inorder: 先访问左子树,然后访问根节点,最后访问右子树. 后序Postorder:先访问左子树,然后访问右子树,最后访问根节点. classNode:def__init__(self,key):self.left=Noneself.right=Noneself.val=keydefprintInorder(root):ifroot...
*/classSolution{public List<Integer>inorderTraversal(TreeNode root){List<Integer>result=newLinkedList<>();TreeNode current=root;TreeNode prev=null;while(current!=null){// left firstif(current.left==null){result.add(current.val);current=current.right;}// if there is left, get the rightmost ...
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与Inorder很相似,但是比Inorder复杂的地方是如何判断该节点的左右子树都已经访问过了,按照Inorder的写法左子树还是先被访问,没有问题,但是访问完左子树后不能直接访问当前节点,要判断当前节点的右子树是否已经被访问,如果没有访问则应该继续去访问右子树,最后再访问当前节点 1vector<int> postorderTraversal(T...
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 ||...
1、preorder + inorder 第一个版本,使用坐标范围: 1/**2* Definition for binary tree3* struct TreeNode {4* int val;5* TreeNode *left;6* TreeNode *right;7* TreeNode(int x) : val(x), left(NULL), right(NULL) {}8* };9*/10classSolution {11public:12TreeNode *build(vector<int> ...
方法一:和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});while(!
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?
public void preorderTraversal(List<Integer> result, TreeNode root){ if(root==null) return; result.add(root.val); preorderTraversal(result, root.left); preorderTraversal(result, root.right); } public void postorderTraversal(List<Integer> result, TreeNode root){ ...
(root); } public void preOrderTraversal() { preOrderTraversal(root); } /* Internal private method to do in order traversal.We will pass the root node to start with and will visit the tree recursively using the following path left-current-right */ private void inOrderTraversal(Node node)...