Would show you the tackle various tree questions using iterative inorder traversal. First one is the iterative inorder traversal using stack. Hope everyone agrees with this solution.
Question:binary Tree inorder Traversal
PublicList<integer>inordertraversal (TreeNode root) {List<Integer> list =NewArraylist<>(); if(Root = =NULL)returnlist; Stack<TreeNode> stack =NewStack<>(); while(Root! =NULL|| !Stack.empty ()) { while(Root! =NULL) {Stack.push (root); Root=Root.left; } Root=Stack.pop (); List.add (Root.val); Root=Root.right; } returnlist;}
Now, we can use this structure to find the Kth smallest element in BST.
question:kth smallest Element in a BST
Public intKthsmallest (TreeNode root,intk) {Stack<TreeNode> stack =NewStack<>(); while(Root! =NULL|| !Stack.isempty ()) { while(Root! =NULL) {Stack.push (root); Root=Root.left; } Root=Stack.pop (); if(--k = = 0) Break; Root=Root.right; } returnRoot.val;}
We can also use this structure to solve BST validation question.
Question:validate Binary Search Tree
Public BooleanIsvalidbst (TreeNode root) {if(Root = =NULL)return true; Stack<TreeNode> stack =NewStack<>(); 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)