非递归代码如下: 1publicArrayList<Integer> inorderTraversal(TreeNode root) { 2ArrayList<Integer> res =newArrayList<Integer>(); 3if(root ==null) 4returnres; 5LinkedList<TreeNode> stack =newLinkedList<TreeNode>(); 6while(root!=null|| !stack.isEmpty()){ 7if(root!=null){ 8stack.push(root...
1/**2* Definition for a binary tree node.3* public class TreeNode {4* int val;5* TreeNode left;6* TreeNode right;7* TreeNode(int x) { val = x; }8* }9*/10publicclassSolution {11publicList<Integer>inorderTraversal(TreeNode root) {12List<Integer> ls =newArrayList<Integer>();13...
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,...
public TreeNode buildTree(int[] inorder, int[] postorder) { postEnd = postorder.length - 1; return helper(postorder, inorder, 0, inorder.length - 1); } private TreeNode helper(int[] postorder, int[] inorder, int inStart, int inEnd){ if(postEnd < 0 || inStart > inEnd){ ret...
1. Problem Descriptions:Given two integer arrays inorderandpostorderwhereinorderis the inorder traversal of a binary tree andpostorderis the postorder traversal of the same tree, construct and retu…
102. 二叉树的层序遍历 - 给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。 示例 1: [https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg] 输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]]
名字叫做, 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...
这道题和LeetCode笔记:107. Binary Tree Level Order Traversal II是姊妹题,解题思路都是一样的,只是结果要求的顺序是反的,同样有两种方法,也就是经常说到的DFS深度优先遍历和BFS广度优先遍历。 BFS: 广度优先遍历就是一层层地攻略过去,把每一层的所有节点都记录下来再走向下一层。因为每层会有多个节点,不是简...
105. 从前序与中序遍历序列构造二叉树 - 给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。 示例 1: [https://assets.leetcode.com/uploads/2021/02/19/tree.jpg] 输入: preo
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} * };*/classSolution {public: vector<vector<int> > levelOrderBottom(TreeNode *root) { vector<vector<int>>res; vector<int>tmp; queue<TreeNode *>Qpre,Qcurr;if(root==NULL)returnres;else{ ...