1classSolution {2public:3vector<int> inorderTraversal(TreeNode *root) {4vector<int>result;5TreeNode *p =root;6while(p) {7if(p->left) {8TreeNode *q = p->left;9while(q->right && q->right !=p) {10q = q->right;11}12if(q->right ==p) {13result.push_back(p->val);14q-...
当前节点更新为当前节点的右孩子。 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:12vector<int> inorderTraversal(TreeNode *root) {...
Python 代码 fromcollectionsimportdeque# 定义二叉树节点classTreeNode:def__init__(self,val=0,left=None,right=None):self.val=valself.left=leftself.right=rightdeflevelOrder(root):# 如果根节点为空,返回空列表ifnotroot:return[]# 初始化队列和结果列表queue=deque([root])result=[]whilequeue:level_siz...
private void pushAllTheLeft(Stack<TreeNode> s, TreeNode root){ s.push(root); while(root.left!=null){ root = root.left; s.push(root); } } } Binary Tree Postorder Traversal Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary tree {1,...
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代码解释 ...
Leetcode 94: Binary Tree Inorder Traversal-中序遍历 自动驾驶搬砖师 一步一个台阶,一天一个脚印 一、题目描述 给定一个二叉树,返回它的中序遍历。 二、解题思路 2.1 递归法 时间复杂度 O(n) 空间复杂度 O(n) 2.2 迭代法 时间复杂度 O(n) 空间复杂度 O(n)(...
从大的层面讲,Binary Tree 可以用DFS和BFS。 对于BFS,我们需要iterative with queue。 对于DFS,Binary Tree 有三种traversal的方式: ** Inorder Traversal: left -> root -> right ** Preoder Traversal: root -> left -> right ** Postoder Traveral: left -> right -> root ...
Morris traversal: My code: /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassSolution{publicList<Integer>preorderTraversal(TreeNoderoot){List<Integer>ret=newArrayList<...
Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] 1. 2. Return the following binary tree: ...
144Binary Tree Preorder TraversalPython1. Recursion, O(n) and O(n) 2. Stack, O(n) and O(n) 145Binary Tree Postorder TraversalPython1. Recursion, O(n) and O(n) 2. Stack and queue (insert 0), O(n) and O(n) 3. Stack and isinstance(curr, TreeNode), O(n) and O(n) ...