码迷,mamicode.com
首页 > 移动开发 > 详细

leetcode--Learn one iterative inorder traversal, apply it to multiple tree questions (Java Solution)

时间:2017-09-01 00:55:57      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:als   rsa   boolean   tac   everyone   push   question   new   validate   

 will show you all how to tackle various tree questions using iterative inorder traversal. First one is the standard iterative inorder traversal using stack. Hope everyone agrees with this solution.

Question : Binary Tree Inorder Traversal 

public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<>();
    if(root == null) return list;
    Stack<TreeNode> stack = new Stack<>();
    while(root != null || !stack.empty()){
        while(root != null){
            stack.push(root);
            root = root.left;
        }
        root = stack.pop();
        list.add(root.val);
        root = root.right;
        
    }
    return list;
}

Now, we can use this structure to find the Kth smallest element in BST.

Question : Kth Smallest Element in a BST 

 public int kthSmallest(TreeNode root, int k) {
     Stack<TreeNode> stack = new Stack<>();
     while(root != null || !stack.isEmpty()) {
         while(root != null) {
             stack.push(root);    
             root = root.left;   
         } 
         root = stack.pop();
         if(--k == 0) break;
         root = root.right;
     }
     return root.val;
 }

We can also use this structure to solve BST validation question.

Question : Validate Binary Search Tree 

public boolean isValidBST(TreeNode root) {
   if (root == null) return true;
   Stack<TreeNode> stack = new Stack<>();
   TreeNode pre = null;
   while (root != null || !stack.isEmpty()) {
      while (root != null) {
         stack.push(root);
         root = root.left;
      }
      root = stack.pop();
      if(pre != null && root.val <= pre.val) return false;
      pre = root;
      root = root.right;
   }
   return true;
}

 

leetcode--Learn one iterative inorder traversal, apply it to multiple tree questions (Java Solution)

标签:als   rsa   boolean   tac   everyone   push   question   new   validate   

原文地址:http://www.cnblogs.com/shihuvini/p/7461195.html

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