zoukankan      html  css  js  c++  java
  • LeetCode -- Binary Tree Inorder Traversal

    Question:

    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?

    Analysis:

    给出一棵二叉树,返回它节点值的中序遍历。

    Note:递归的解决方案是简单的,你能用循环的方式解决吗?

    思路1:递归的解决方案:

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

    思路二:非递归遍历方式。使用一个栈,记录遍历过程中回退的路径。在一棵子树中首先访问的是中序下的第一个结点,它位于从根开始沿leftChild链走到最左下角的结点。访问它的数据之后,再遍历该结点的右子树。重复以上过程。

    /**
     * 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<Integer>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode p = root;
            do {
                while(p != null) {
                    stack.push(p);
                    p = p.left;
                }
                if(!stack.isEmpty()) {
                    p = stack.pop();
                    list.add(p.val);
                    p = p.right;
                }
            } while(p != null || !stack.isEmpty());
            return list;
        }
    } 
  • 相关阅读:
    StringUtils
    改变windows锁屏时间
    data-toggle和data-target
    Bootstrap元素居中
    爬虫软件/程序
    nfs服务器搭建
    浏览器控制台console对象的使用
    F7
    Ubuntu18.04 安装Docker【转】
    mysql出现ERROR1698(28000):Access denied for user root@localhost错误解决方法【转】
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5233655.html
Copyright © 2011-2022 走看看