The binary tree traversal sequence (94)

Description Title: Given a binary tree in preorder to return it.
Example:
  Input: [. 1, null, 2,3]
       . 1
        \
         2
        /
       . 3
Output: [1,3,2]

 

Solution one: recursion (simpler)    

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<Integer> lis = new ArrayList<>(); 
    public List<Integer> inorderTraversal(TreeNode root) {
        IF (the root == null)     return  LIS; // If the node is empty, the current results returned array
        inorderTraversal (root.left); // left subtree preorder
        lis.add(root.val);          
        inorderTraversal (root.right); // right subtree to be preorder
        return lis;
    }
}
 
解法二:(迭代)--基于栈的中序遍历
class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            Stack<TreeNode> stack = new Stack<>();
            TreeNode cur = root;
            while (cur != null || !stack.isEmpty()) {
                if (cur != null) {
                    stack.push(cur);//保留当前根节点信息
                    cur = cur.left;
                } else {
                    cur = stack.pop();
                    list.add(cur.val);
                    cur = cur.right;
                }
            }
            return list;
        }
    }

Guess you like

Origin www.cnblogs.com/zrx-1022/p/12375483.html
Recommended