TreeNode *pNodeA6 = CreateBinaryTreeNode(4); TreeNode *pNodeA7 = CreateBinaryTreeNode(7); ConnectTreeNodes(pNodeA1, pNodeA2, pNodeA3); ConnectTreeNodes(pNodeA2, pNodeA4, pNodeA5); ConnectTreeNodes(pNodeA5, pNode
left); traversal(root.right); result.add(root.val); } } 复杂度分析 时间复杂度:O(n),其中 n 是二叉树的节点数。每一个节点恰好被遍历一次 空间复杂度:O(n),为递归过程中栈的开销,平均情况下为 O(logn),最坏情况下树呈现链状,为 O(n) 迭代法 /** * Definition for a binary tree node....
classSolution {public: vector<int> postorderTraversal(TreeNode *root) { vector<int>res;if(root==NULL)returnres; stack<pair<TreeNode*,int>>s;intunUsed; s.push(make_pair(root,1));while(!s.empty()) { root=s.top().first; unUsed=s.top().second; s.pop();if(unUsed){ s.push(make...
publicList<Integer>postorderTraversal(TreeNoderoot){List<Integer>list=newArrayList<>();if(root==null){returnlist;}Stack<TreeNode>stack=newStack<>();stack.push(root);stack.push(root);while(!stack.isEmpty()){TreeNodecur=stack.pop();if(cur==null){continue;}if(!stack.isEmpty()&&cur==stac...
Given a binary tree, return thepostordertraversal of its nodes' values. For example: Given binary tree{1,#,2,3}, 1 \ 2 / 3 1. 2. 3. 4. 5. return[3,2,1]. Note:Recursive solution is trivial, could you do it iteratively?
给定一个二叉树,返回它的后序遍历。 示例: 输入:[1,null,2,3] 1 \ 2 / 3输出:[3,2,1] 1. 2. 3. 4. 5. 6. 7. 8. 进阶:递归算法很简单,你可以通过迭代算法完成吗? DFS 今天这道题比较简单,直接DFS就可以了。 Code def postorderTraversal(self, root: TreeNode) -> List[int]: ...
1) Preorder traversal Totraverse a binary tree in preorder, following operations are carried out: Visit the root. Traverse the left sub tree of root. Traverse the right sub tree of root. Note:Preorder traversal is also known as NLR traversal. ...
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 代码语言:javascript 代码运行次数:0 运行 AI代码解释 ...
*/class Solution{public:vector<int>postorderTraversal(TreeNode*root){vector<int>res;if(!root)returnres;stack<TreeNode*>st;st.push(root);while(st.size()){TreeNode*temp=st.top();st.pop();res.push_back(temp->val);if(temp->left)st.push(temp->left);if(temp->right)st.push(temp->ri...
Solution{public:vector<int>postorderTraversal(TreeNode*root){vector<int>result;stack<TreeNode*>st;TreeNode*p=root,*q=NULL;do{while(p)st.push(p),p=p->left;q=NULL;while(!st.empty()){p=st.top();st.pop();if(p->right==q)//右子树为空或者已经访问{result.push_back(p->val);q=p...