LeetCode 第94题 二叉树的中序遍历

给定一个二叉树,返回它的中序 遍历。

示例:

输入: [1,null,2,3]
1
\
2
/
3

输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?


 1 class Solution94 {
 2 
 3   List<Integer> res = new ArrayList<>();
 4 
 5 
 6   //递归
 7   public List<Integer> inorderTraversal(TreeNode root) {
 8     search(root);
 9     return res;
10   }
11 
12   void search(TreeNode root) {
13     if (root == null) {
14       return;
15     }
16 
17     if (root.left != null) {
18       search(root.left);
19     }
20     res.add(root.val);
21     if (root.right != null) {
22       search(root.right);
23     }
24   }
25 
26   //非递归1
27   public List<Integer> inorderTraversal_2(TreeNode root) {
28     Stack<TreeNode> stack = new Stack<>();
29     while (root != null) {
30       stack.push(root);
31       root = root.left;
32     }
33 
34     while (!stack.isEmpty()) {
35       TreeNode node = stack.pop();
36       res.add(node.val);
37       if (node.right != null) {
38         stack.add(node.right);
39         TreeNode leftNode = node.right.left;
40         while (leftNode != null) {
41           stack.add(leftNode);
42           leftNode = leftNode.left;
43         }
44       }
45     }
46 
47     return res;
48   }
49 
50 
51   //非递归2
52   public List<Integer> inorderTraversal_3(TreeNode root) {
53     Stack<TreeNode> stack = new Stack<>();
54     TreeNode currNode = root;
55 
56     while (currNode != null || !stack.isEmpty()) {
57       while (currNode != null) {
58         stack.push(currNode);
59         currNode = currNode.left;
60       }
61 
62       /*
63       运行到此时,currNode必定为null (可能是访问空的左孩子,也可能是访问空的右孩子)
64       不过他们有一个共同的特点: 都需要跳转到栈顶元素,并且访问栈顶元素.(父节点或者是父节点的父节点)
65       一旦栈顶元素被访问,根据中序遍历特点,接下来一定访问右子树.
66       */
67       currNode = stack.pop();
68       res.add(currNode.val);
69       currNode = currNode.right;
70 
71     }
72 
73     return res;
74   }
75 }

猜你喜欢

转载自www.cnblogs.com/rainbow-/p/10492835.html