zoukankan      html  css  js  c++  java
  • 94. Binary Tree Inorder Traversal (Java)

    Given a binary tree, return the inorder traversal of its nodes' values.

    Example:

    Input: [1,null,2,3]
       1
        
         2
        /
       3
    
    Output: [1,3,2]

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

    法I:递归

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            if(root == null) return result;
            inorder(root);
            return result;
        }
        
        public void inorder(TreeNode root) {
            if(root.left!=null) inorder(root.left);
            result.add(root.val);
            if(root.right!=null) inorder(root.right); 
        }
        
        private List<Integer> result = new ArrayList<Integer>();
    }

    法II:循环。使用stack以及一个set标记当前节点是否访问过

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> result = new ArrayList<Integer>();
            Set<TreeNode> visitedSet = new HashSet<TreeNode>();//Set有HashSet和TreeSet两种实现
            if(root == null) return result;
            Stack<TreeNode> s = new Stack<TreeNode>();
            TreeNode curNode = root;
            while(true){
                if(visitedSet.contains(curNode)){ //如果访问过,访问右儿子
                    result.add(curNode.val);
                    curNode = curNode.right;
                }
    
                while(curNode!=null){ //如果没有访问过,自己先进栈,然后是左儿子         
                    s.push(curNode);
                    visitedSet.add(curNode);
                    curNode = curNode.left;
                }
                if(s.empty()) break;
                
                //出栈一个节点
                curNode = s.peek();
                s.pop();
            }
            
            return result;
        }
    }
  • 相关阅读:
    C/C++中volatile关键字详解(转)
    Spring中 @Autowired标签与 @Resource标签 的区别(转)
    [转]各种互斥量的总结
    nginx限制ip访问(转)
    HDU 4833 Best Financing (DP)
    HDU 4832 Chess (DP)
    HDU 4831 Scenic Popularity
    POJ 2155 Matrix (二维线段树)
    POJ 2155 Matrix (二维树状数组)
    HDU 4819 Mosaic (二维线段树)
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/11224794.html
Copyright © 2011-2022 走看看