LeetCode: Binary Tree Inorder Traversal 解题报告

时间:2021-04-22 13:04:15

Binary Tree Inorder Traversal

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?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

SOL:

包括递归与非递归方法:

 /**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal1(TreeNode root) {
List<Integer> ret = new ArrayList<Integer>();
rec(root, ret);
return ret;
} public void rec(TreeNode root, List<Integer> ret) {
if (root == null) {
return;
} rec(root.left, ret);
ret.add(root.val);
rec(root.right, ret);
} public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<Integer>();
if (root == null) {
return ret;
} Stack<TreeNode> s = new Stack<TreeNode>();
TreeNode cur = root; while (true) {
while (cur != null) {
s.push(cur);
cur = cur.left;
} if (s.isEmpty()) {
break;
} cur = s.pop();
ret.add(cur.val); cur = cur.right;
} return ret;
}
}