public List<Integer> inorderTraversal(TreeNode root) { /** * 中序遍历,先左子树,再根,最后右子树 */ if(root == null) return list; if(root.left != null){ inorderTraversal(root.left); } list.add(root.val); if(root.right != null){ inorderTraversal(root.right); } return list; }...
public: vector<int> inorderTraversal(TreeNode *root) { vector<int> ans; inorder(root,ans); return ans; } void inorder(TreeNode *node,vector<int>&ans) { if(node == NULL) return; inorder(node->left,ans); ans.push_back(node->val); inorder(node->right,ans); } }; /** * Def...
https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ 给定两个整数数组preorder和inorder,其中preorder是二叉树的先序遍历,inorder是同一棵树的中序遍历,请构造二叉树并返回其根节点。 示例1: 输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] 输出...
definorderTraversal(self,root):res,stack=[],[]whilestackorroot:ifroot:stack.append(root)root=root.leftelse:node=stack.pop()res.append(node.val)root=node.rightreturnres 3. 后序遍历 145. 二叉树的后序遍历 后序遍历,输出为[1,2,3,4,5] 递归 definorderTraversal(self,root):res=[]defhelpe...
Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. 翻译:给定树的前序和中序遍历,构造二叉树。 注意: 树中不存在重复项。 思路:首先,你应该知道 前序遍历:根节点,左子树,右子树; ...
名字叫做, morrois 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>inorderTraversal(TreeNoderoot){List...
inorderTraversal(root.left); //根的值放进去 res.add(root.val); inorderTraversal(root.right); } return res; } } 时间复杂度:O(n),其中n为二叉树节点的个数。二叉树的遍历中每个节点会被访问一次且只会被访问一次。 空间复杂度:O(n)。空间复杂度取决于递归的栈深度,而栈深度在二叉树为一条链的...
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/ Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. 题意 给定一个整数 n,生成所有由 1 ... n 为节点所组成的 二叉搜索树 。
代码语言:javascript 复制 type TreeNode struct{Val int Left*TreeNode Right*TreeNode}funcbuildTree(preorder[]int,inorder[]int)*TreeNode{iflen(preorder)==0{returnnil}res:=&TreeNode{Val:preorder[0],}iflen(preorder)==1{returnres}idx:=func(val int,nums[]int)int{fori,v:=range nums{ifv...
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: inorderList = [] stack = [] while stack or root: while root: stack.append(root) root = root.left...