題目:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
題解:
中序遍歷:遞迴左 處理當前 遞迴右。
畫圖的話就是,之前離散老師教的,從root開始沿著子樹畫線,遍歷完全樹,每一個被畫線畫到2次的就表示遍歷到了,依次寫出就行了。
遞迴程式碼如下:
1 public void helper(TreeNode root, ArrayList<Integer> re){
2 if(root==null)
3 return;
4 helper(root.left,re);
5 re.add(root.val);
6 helper(root.right,re);
7 }
8 public ArrayList<Integer> inorderTraversal(TreeNode root) {
9 ArrayList<Integer> re = new ArrayList<Integer>();
10 if(root==null)
11 return re;
12 helper(root,re);
13 return re;
14 }
2 if(root==null)
3 return;
4 helper(root.left,re);
5 re.add(root.val);
6 helper(root.right,re);
7 }
8 public ArrayList<Integer> inorderTraversal(TreeNode root) {
9 ArrayList<Integer> re = new ArrayList<Integer>();
10 if(root==null)
11 return re;
12 helper(root,re);
13 return re;
14 }
非遞迴程式碼如下:
1 public ArrayList<Integer> inorderTraversal(TreeNode root) {
2 ArrayList<Integer> res = new ArrayList<Integer>();
3 if(root == null)
4 return res;
5 LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
6 while(root!=null || !stack.isEmpty()){
7 if(root!=null){
8 stack.push(root);
9 root = root.left;
10 }else{
11 root = stack.pop();
12 res.add(root.val);
13 root = root.right;
14 }
15 }
16 return res;
17 }
2 ArrayList<Integer> res = new ArrayList<Integer>();
3 if(root == null)
4 return res;
5 LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
6 while(root!=null || !stack.isEmpty()){
7 if(root!=null){
8 stack.push(root);
9 root = root.left;
10 }else{
11 root = stack.pop();
12 res.add(root.val);
13 root = root.right;
14 }
15 }
16 return res;
17 }