二叉树遍历

来源:互联网 发布:js验证用户名是否存在 编辑:程序博客网 时间:2024/06/05 21:59

前序遍历:非递归解法

public class Solution {    /**     * @param root: The root of binary tree.     * @return: Preorder in ArrayList which contains node values.     */    public ArrayList<Integer> preorderTraversal(TreeNode root) {        // write your code here        ArrayList<Integer> result = new ArrayList<Integer>();        Stack<TreeNode> stack = new Stack<TreeNode>();        if(root == null){            return result;        }        stack.push(root);        while(!stack.empty()){            TreeNode temp = stack.pop();            result.add(temp.val);            if(temp.right!=null){                stack.push(temp.right);            }            if(temp.left!=null){                stack.push(temp.left);            }        }        return result;    }}

中序遍历:非递归解法

public class Solution {    /**     * @param root: The root of binary tree.     * @return: Inorder in ArrayList which contains node values.     */    public ArrayList<Integer> inorderTraversal(TreeNode root) {        // write your code here        ArrayList<Integer> result = new ArrayList<Integer>();        Stack<TreeNode> stack = new Stack<TreeNode>();        TreeNode cur = root;        while(cur != null || !stack.empty()){            while(cur != null){                stack.push(cur);                cur = cur.left;            }            cur = stack.peek();            result.add(cur.val);            stack.pop();            cur = cur.right;        }        return result;    }}

后续遍历:递归解法

public class Solution {    /**     * @param root: The root of binary tree.     * @return: Postorder in ArrayList which contains node values.     */    public ArrayList<Integer> postorderTraversal(TreeNode root) {        // write your code here        ArrayList<Integer> result = new ArrayList<Integer>();        if(root == null){            return result;        }        result.addAll(postorderTraversal(root.left));        result.addAll(postorderTraversal(root.right));        result.add(root.val);        return result;    }}


0 0