码迷,mamicode.com
首页 > 其他好文 > 详细

in order traversal

时间:2018-08-09 18:32:47      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:without   color   private   vat   turn   push   nod   function   one   

in order traversal 


/**
 * 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<>();
        if(root == null) return result;
        Stack<TreeNode> stack = new Stack<>();
        pushLeft(root, stack);
        
        while(!stack.isEmpty()){
            TreeNode cur = stack.pop();
            result.add(cur.val);
            
            if(cur.right != null){
                pushLeft(cur.right, stack);
            }
        }
        return result;
    }
    private void pushLeft(TreeNode root, Stack<TreeNode> stack){
        while(root != null){
            stack.push(root);
            root = root.left;
        }
    }
}

///////  recursion with global var 

class Solution {
    List<Integer> result = new ArrayList<>(); // has to be here so theres only one result , the result here is global variable 

    public List<Integer> inorderTraversal(TreeNode root) {
      if(root == null) return result;
      if(root.left != null) inorderTraversal(root.left);
      result.add(root.val);
      if(root.right != null) inorderTraversal(root.right);
      return result;
    }
} 

///////. recursion without global var, with a helper function 


class Solution {
    public List < Integer > inorderTraversal(TreeNode root) {
      List<Integer> result = new ArrayList<>();
      if(root == null) return result;
      helper(root, result);
      return result;
    }
  
    private void helper(TreeNode root, List<Integer> result){
      
      if(root.left != null) helper(root.left, result);
      result.add(root.val);
      if(root.right != null) helper(root.right, result);
    }
}


///
class Solution {
    public List < Integer > inorderTraversal(TreeNode root) {
        List < Integer > res = new ArrayList < > ();
        helper(root, res);
        return res;
    }

    public void helper(TreeNode root, List < Integer > res) {
        if (root != null) {
            if (root.left != null) {
                helper(root.left, res);
            }
            res.add(root.val);
            if (root.right != null) {
                helper(root.right, res);
            }
        }
    }
}

 

in order traversal

标签:without   color   private   vat   turn   push   nod   function   one   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9450624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!