个人记录-LeetCode 94. Binary Tree Inorder Traversal

来源:互联网 发布:端口查看 编辑:程序博客网 时间:2024/06/06 07:41

问题:
Given a binary tree, return the inorder traversal of its nodes’ values.

For example:
Given binary tree [1,null,2,3],

 1    \     2    /   3

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?


代码示例:
1、递归
这个问题其实就是要求我们中序遍历一棵树。
中序遍历其实就是“左中右”,即每一个节点都先输出左字节点,然后输出自己,然后才输出右字节点。
于是容易想到利用递归+栈,代码如下:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> inorderTraversal(TreeNode root) {        //保存结果        List<Integer> rst = new ArrayList<>();        if (root != null) {            //栈用于保存“中”节点            Stack<TreeNode> stack = new Stack<>();            //递归处理            InnerHelper(root, rst, stack);        }        return rst;    }    private void InnerHelper(TreeNode root, List<Integer> rst, Stack<TreeNode> stack) {        //存在左子节点,则保存中间节点到stack        if (root.left != null) {            TreeNode tmp = new TreeNode(root.val);            tmp.left = null;            tmp.right = root.right;            stack.push(tmp);            //然后再继续递归左子节点            root = root.left;            InnerHelper(root, rst, stack);        } else {            //没有左子节点了,就保存“中”节点的值            rst.add(root.val);            //有右子节点,就递归处理右子节点            if (root.right != null) {                InnerHelper(root.right, rst, stack);            } else {                //否则,从stack中取出之前保存的“中”节点,继续递归处理                //实际上,这些“中”节点,最多存在右子树了                if (!stack.isEmpty()) {                    root = stack.pop();                    InnerHelper(root, rst, stack);                }            }        }    }}

2、直接迭代处理
从上文的分析,我们其实可以看出,利用stack即使不递归也能有效的处理该问题。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> inorderTraversal(TreeNode root) {        List<Integer> list = new ArrayList<>();        Stack<TreeNode> stack = new Stack<>();        //主要思路与上文一致,只是用两个while循环替代了递归        while(root != null || !stack.empty()){            while(root != null){                stack.add(root);                root = root.left;            }            root = stack.pop();            list.add(root.val);            root = root.right;        }        return list;    }}
0 0
原创粉丝点击