Showing posts with label Tree. Show all posts
Showing posts with label Tree. Show all posts

Monday, June 17, 2013

Path Sum II (C++ code)

Leetcode Path Sum II, Oct 14 '122982 / 8423
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
return
[
   [5,4,11,2],
   [5,8,4,5]
]
思路:递归。用完某个node之后记得把值pop出来。


  1. void findpath(TreeNode *root, int sum, vector<vector<int>> &res, vector<int> &path){  
  2.   
  3.   if(!root->left && !root->right){  
  4.   
  5.        if(sum == 0) res.push_back(path);  
  6.   
  7.        return;   
  8.   
  9.   }   
  10.   
  11.   if(root->left){  
  12.   
  13.     path.push_back(root->left->val);   
  14.   
  15.     findpath(root->left, sum - root->left->val, res, path);  
  16.   
  17.     path.pop_back();   
  18.   
  19.   }  
  20.   
  21.   if(root->right){   
  22.   
  23.     path.push_back(root->right->val);  
  24.   
  25.     findpath(root->right, sum - root->right->val, res, path);  
  26.   
  27.     path.pop_back();  
  28.   
  29.   }  
  30.   
  31. }   
  32.   
  33.    
  34.   
  35. vector<vector<int> > pathSum(TreeNode *root, int sum) {  
  36.         vector<vector<int>> res;  
  37.   
  38.         vector<int> path;   
  39.   
  40.         if(!root) return res;  
  41.   
  42.         path.push_back(root->val);  
  43.   
  44.         findpath(root, sum - root->val, res, path);  
  45.         return res;  
  46.     }   

Path sum(C++ code)

Leetcode Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
思路:递归。要注意的是valid path必须是从root到leaf,如果只有一边没有孩子 ,是不算叶子的。。


  1. bool hasPathSum(TreeNode *root, int sum) {  
  2.         if(!root) return false;  
  3.         int update = sum - root->val;  
  4.         if(!root->left && !root->right) return (update == 0)? true : false;  
  5.         return hasPathSum(root->left, update)  ||  hasPathSum(root->right, update);  
  6.     }   

Thursday, May 23, 2013

find next node of a tree(C++)

写的啥啊看不懂。。重新写一个。。
------06/17/13 rewrite-----------
假设不是最大的节点 ,假设是BST
1, node has  a parent field.
node *nextNode(node *root,  int val){
    if(!root) return NULL;
   while(root && root->val != val){
       if(root->val > val) root = root->left;
       else root = root->right;
   }
   if(!root->right) return root->parent;
   root = root->right;
   while(root->left){
       root = root->left;
   }
   return root;
}

2, node doesn't have a parent field.

node *nextNode(node *root,  int val){
   if(!root) return NULL;
   node dummy(0);
   dummy.next = root;
   node *parent = &dummy;
   // find node with value = val
   while(root && root->val != val){
       parent = root;
       if(root->val > val) root = root->left;
       else root = root->right;
   } 
   // find next node
   if(!root->right) return parent;
   root = root->right;
   while(root->left){
       root = root->left;
   }
   return root;
}


------------------old post---------------------------
add a successor pointer for each node in a tree

findsuc(node *root){
  node *parent = NULL;
  node *first,last;
  inorder(root,  first, last);
}

void inorder(node *root,  node *first, node *last){
  if(!root->left) first = root;
  if(!root->right) last = root;
  if(root->left){
   inorder(root->left, first, last);
   last->successor = root;
  }
  if(root->right) {
   inorder(root->right,first,last);
   root->sucessor = first;
   last->successor = NULL;
  }
}
---------------
void solve(Node * r) {
    while (r && r->left) r=r->left;
    Helper(NULL, r);
}

// return the last node of inorder travsal
Node * Helper(Node * prev, Node * r) {
    if (!r) return NULL;
    Node * prev_in_left = Helper(prev, r->left);

    if (prev_in_left) prev = prev_in_left;
    if (prev) prev->successor = r;

    return r->right?Helper(r, r->right):r;
}

quadtree (C++)

问题1 : 为这个 quadtree里面的 node 设计 data structure

然后的问题是关于两个 quadtree 的 intersection, 有两个 quadtree, 它们描述的 
image 是两个相同的 area
比如 都是 [0 1] x [0 1] 这个相同的二维区域的image.

问题二: 写一个函数,返回两个 quadtree的intersection,

这个intersection的规则是: 如果一个区域在 第一个quadtree 里面是
白的,这个相同的区域在 第二个 quadtree里面是黑的,那么intersection
就是白的,简单的说白是 0, 黑是 1, intersection就是两个bit 的 AND
-------------------
//color: 0 means white, 1 means black, 2 means mixed.
struct Qnode{
private:
  int color; 
  Qnode *children;
public:
  Qnode(int c){color = c;};




Qnode *intersection(Qnode *first, Qnode *second){
   if(first == NULL && second == NULL)
 // if both nodes are mixed
  if(first->color == 2 && second->color == 2){
    Qnode *root = new Qnode(2);
    Qnode *newchildren = new Qnode[4];
    int count = 0;
    for(i = 0; i < 4; i++){
    newchildren[i] = intersection(first->children[i], second->children[i]); 
    if(newchildren[i]->color == 0) count++;  
    }
   if(count == 4){
     root->color = 0;
     delete[] newchildren;
   }  
 } 

//if at least one is while
else if(first->color == 0 || second->color == 0)  
  Qnode *root = new Qnode(0);
  root->children = NULL;


//if one black one mixed or two blacks
else if(first->color == 1) Qnode *root =clone(second);
else (second->color == 1) Qnode *root = clone(first);

return root;
 }

Qnode *clone(Qnode *quad){
  if(quad == NULL) return Null;
  Qnode *root = new Qnode(quad->color);
  if(!quad->children) root->children == NULL; 
  else 
for(int i = 0; i < 4; i++){
 root->children[i] = clone(quad->children[i]);
}

return root;
}



Saturday, May 11, 2013

Validate binary search tree(C++ code)

LeetCode Validate Binary Search Tree, Aug 31 '12
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.
思路:这题简单,一次bug free。。。最近都在科普python,sql ,为了避免C++手生,决定每天练一道leetcode,恩,发现C还是很重要的,把C搞懂了,学其他的才会事半功倍~
  1. #helper function  
  2. bool isValidBST(TreeNode *root, int lower, int upper){  
  3.   
  4.  if (!root) return true;  
  5.   
  6.  if(root->val <= lower || root->val >= upper) return false;  
  7.   
  8.  bool left = isValidBST(root->left, lower, root->val);  
  9.   
  10.  bool right = isValidBST(root->right, root->val, upper);  
  11.   
  12.    
  13.   
  14.  return left && right;  
  15.   
  16. }  
  17.   
  18. bool isValidBST(TreeNode *root) {  
  19.         isValidBST(root, INT_MIN, INT_MAX);  
  20.          
  21.     }   

Wednesday, May 8, 2013

minimum depth of binary tree(c++ code)

LeetCode Minimum Depth of Binary Tree, Oct 10 '121893 / 4635
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
思路:递归

  1. int minDepth(TreeNode *root) {  
  2.        if(!root) return 0;  
  3.        if(!root->left && !root->right) return 1;  
  4.        int leftmin = INT_MAX, rightmin = INT_MAX;  
  5.        if(root->left){  
  6.           leftmin = minDepth(root->left);  
  7.        }  
  8.        if(root->right){  
  9.            rightmin = minDepth(root->right);  
  10.        }  
  11.        return min(leftmin, rightmin) + 1;  
  12.          
  13.    }  

Wednesday, April 24, 2013

Sum Root to Leaf NumbersFeb 191675 / 4693
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
    1
   / \
  2   3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.

-----------乌龙的分割线oops..--------------正解随后---------------
我这什么记性啊,看完题目去睡觉,然后睡前想了下,自以为想出来了,今天早上唰唰写好 code, 放到OJ一测试,没过,仔细一看,原来我答非所问,完全做的另外一道题!!为了不浪费劳动成果,还是贴在这把,我做的题是:对每条root-to-leaf path求和,最后得出总和,比如
  1
2  3
得到的就是(1+2)+(1+3) = 7.

void postorder(TreeNode *root, int &sum, unordered_map<TreeNode *, int> &count){
   if(!root) return;
   if(!root->left && !root->right) {
     count[root] = 1;
     sum += root->val;
     return;
  }
   postorder(root->left, sum, count);
   postorder(root->right,sum,count);
   count[root] = 0;
   if(root->left) count[root] +=  count[root->left];
   if(root->right) count[root] += count[root->right];
   sum += root->val * count[root];
  
}

int sumNumbers(TreeNode *root) {
       int sum = 0;
unordered_map<TreeNode *, int> count;
       postorder(root, sum,count);
       
      return sum;
    }

------------------正解my solution-------------------后面有更优解-------------
还好思路也差不多,还更简单,建个map对每个node重新赋值就好了
void preorder(TreeNode *root, int &sum, unordered_map<TreeNode *, int> &num){
   if(!root->left && !root->right) {
     sum += num[root];
     return;
  }

  if(root->left) {
     num[root->left] = num[root] *10 + root->left->val;
     preorder(root->left, sum, num);
  }                  
  if(root->right) {
     num[root->right] = num[root] *10 + root->right->val;
     preorder(root->right, sum, num);
  }
}

int sumNumbers(TreeNode *root) {
      if(!root) return 0;
      int sum = 0;
unordered_map<TreeNode *, int> num;
      num[root] = root->val;
       preorder(root, sum, num);
       
      return sum;
    }
-------------最优解best solution-----------------
写完上面的解后,觉得这个map挺多余的,应该能去掉,但是懒得弄了,于是找了个别人的code(lu-an gong at Leetcode),就是用一个动态number代替map,每次做到leaf node这个number就回去一个,如果做完右子树再回去一个。


  1. int sumNumbers(TreeNode *root) {  
  2.     int num = 0, sum = 0;  
  3.     sumNumbersImpl(root, num, sum);  
  4.     return sum;  
  5. }  
  6.   
  7. void sumNumbersImpl(TreeNode *root, int& num, int& sum) {   
  8.     if (root == nullptr) return;   
  9.     num = num * 10 + root->val;   
  10.     if (root->left == nullptr && root->right == nullptr) {   
  11.        sum += num;   
  12.     }   
  13.     else {   
  14.        sumNumbersImpl(root->left, num, sum);   
  15.        sumNumbersImpl(root->right, num, sum);   
  16.     }   
  17.     num /= 10;   
  18. }  

Tuesday, April 23, 2013

Find nearest m nodes for a key in BST(C++ code)

面试题。
先写个O(n)的,用in order traversal, 用queue存m个,每次尾巴新进来一个,跟头做比较,因为queue里面的元素是in order的, 如果新尾巴比头更接近key,就把头挤掉。如果不比头更接近,说明已经完成,就return queue。

queue<node *> findmclosest(node * root, int key,  int m){
      queue<node *> q;
     findhelper(root, key, q, m);
     return q;
}

void findhelper(node *root, int key, queue<node *> q, int m){
     if(root == NULL) return;
     findhelper(root->left, key, q, m);
     if(q.size() < m) q.push(root->val);
     else{
         int diff = abs(root->val - key);
         if(diff >= abs(q.front() - key) ) return;
         else{
            q.pop();
            q.push(root);
        }
     }
     findhelper(root->right, key, q, m);
}


接下来是复杂一点的O(m*log n),思路是先找到key,一边找一边用两个m sized queue存经过的节点,
pre: 存放比key小的节点
next:存放比key大的节点
pre:每次pop元素后,要考虑该元素的左子树, next:每次pop后,要考虑该元素的右子树
用logn的时间找到节点后,注意到pre和next都是尾巴上的点跟key值最接近,就直接从尾巴一个一个取就好了。
 //push next(min element of right subtree) and push pre(max element of left subtree)
void nextpush(node *tmp, deque<node *> &next)
while(tmp){
     if(next.size() >= m) next.pop_front();
     next.push(tmp);
     tmp = tmp->left;
   }
}

void prepush(node *tmp, deque<node *> &pre)
while(tmp){
     if(pre.size() >= m) pre.pop_front();
     pre.push(tmp);
     tmp = tmp->right;
   }
}

//find key node
void findkey(node *root, int key, deque<node *> &pre, deque<node *> &next, int m){
  if(!root) return;
  if(root->val <= key){
    if(pre.size() >= m) pre.pop();
    pre.push(root); 
    findkey(root->right, key, pre, next, m);
  }
 if(root->val >= key){
   if(next.size() >= m) next.pop();
    next.push(root); 
    findkey(root->left, key, pre, next, m); }
}


vector<int> findmclosest(node *root, int key, int m){
  int i = 0;
  vector<int> res;
  deque<node *> pre;
  deque<node *>next;
  node *tmp;
  findkey(root, key, pre,next, m);
//deal with key found in tree
 if(!pre.empty() && !next.empty &&pre.back() == next.back()){
   res[i++] = key;
   tmp = pre.back()->left;
   pre.pop_back();
   prepush(tmp,pre);
   tmp = next.back()->right;
   next.pop_back();
   nextpush(tmp,next);
 }

//start comparing and setting up result nodes.
while(!pre.empty() && !next.empty()){
  int prenode = pre.back();
  int nextnode = next.back();
  if(key - prenode->val > nextnode->val - key ) {
      res[i++] = nextnode->val;
      if(i == m) return res;
      next.pop_back();
      nextpush(nextnode->right, next);
  }
 else{
     res[i++] = prenode->val;
      if(i == m) return res;
      pre.pop_back();      prepush(prenode->left, pre);
  }
}

//when pre/next used up before getting m nodes

while(!pre.empty()){
   res[i++] = prenode->val;
      if(i == m) return res;
      pre.pop_back();   
   prepush(prenode->left, pre);
}

while(!next.empty()){
   res[i++] = nextnode->val;
      if(i == m) return res;
      next.pop_back();   
   nextpush(nextnode->right, next);
}

 return res;

}

Thursday, April 18, 2013

serialization/deserialization of a binary tree(C++ code)

Leetcode Serialization/Deserialization of a Binary Tree

Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called ‘serialization’ and reading back from the file to reconstruct the exact same binary tree is ‘deserialization’.

Assume we have a binary tree below:
    _30_ 
   /    \    
  10    20
 /     /  \ 
50    45  35
Using pre-order traversal, the algorithm should write the following to a file:
30 10 50 # # # 20 45 # # 35 # #

这个OJ没有,当面试题准备做做。
  1. void writeBinaryTree(TreeNode *p, ostream &out) {  
  2.   
  3.   if(!p) {out<<"# "return;}  
  4.   
  5.   out<<p->val<<" ";  
  6.   
  7.   writeBinaryTree(p->left, out);  
  8.   
  9.   writeBinaryTree(p->right, out);  
  10.   
  11. }   
 
  1. void readBinaryTree(TreeNode *&p, ifstream &fin){  
  2.   
  3.   if(fin.eof()) return;  
  4.   
  5.   string value;  
  6.   
  7.   value<<fin;  
  8.   
  9.   int number ;  
  10.   
  11.   if( istringstream(value)>>number){  
  12.   
  13.   p = new TreeNode(number);  
  14.   
  15.   readBinaryTree(p->left, fin);  
  16.   
  17.   readBinaryTree(p->right,fin);  
  18.   
  19.   }  
  20.   
  21. }   


Monday, April 15, 2013

Convert Sorted Array to Binary Search Tree (C++ code)

LeetCode Convert Sorted Array to Binary Search Tree, Oct 2 '12
 G家面试题,写一个吧。
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

TreeNode *sortedArrayToBST(vector<int> &num, int start, int end){
    if(start > end) return NULL;
    int mid = (start + end)/2;
    TreeNode *root = new TreeNode(num[mid]);
    root->left = sortedArrayToBST(num, start, mid - 1);
    root->right = sortedArrayToBST(num, mid+1, end);

   return root;
}


TreeNode *sortedArrayToBST(vector<int> &num) {
       if(num.size() == 0) return NULL; 

       return sortedArrayToBST(num, 0, num.size() - 1); 
       
    }


Friday, April 12, 2013

Flatten binary tree to linked list

LeetCode Flatten Binary Tree to Linked List, Oct 14 '12
难度3,出现频率3
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
         1
        / \
       2   5
      / \   \
     3   4   6
The flattened tree should look like:
   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6
思路: 用递归挺简单的--第一个一次通过bug free的代码,oh yeah! 
void flatten(TreeNode *root) {
      if(root == NULL) return;  
      flatten(root->left);
      flatten(root->right);
      TreeNode *temp = root->right; 
      root->right = root->left;
      root->left = NULL;
      TreeNode *cur = root;
      while(cur->right != NULL){
        cur = cur->right;
      cur->right = temp;
    } 

Wednesday, April 10, 2013

Convert Sorted List to Binary Search Tree(C++ code)

LeetCode Convert Sorted Array to Binary Search Tree, Oct 2 '12
难度2,出现频率3
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
思路: 每次找中间位置的node,设为root,左孩子是左半边的根,右孩子是右半边的根。
tips:左半边并不是以NULL node结束的,写判断条件的时候要注意。

TreeNode *findroot(ListNode *head, ListNode *tail){

    if(head == NULL) return NULL;

    if(head == tail) {

       TreeNode *root = new TreeNode(head->val);

      root->left = NULL; root->right = NULL;

      return root;

    }

    ListNode *slow = head, *fast = head->next;

    while(fast != tail && fast->next != tail){
     
       slow = slow->next;

       fast = fast->next->next;

    }

    TreeNode *root = new TreeNode(slow->next->val);

    root->left = findroot(head, slow);

    if(slow->next == tail) root->right = NULL;
    else root->right = findroot(slow->next->next, tail);
return root;


}

TreeNode *sortedListToBST(ListNode *head) {

      if(head == NULL) return NULL;

      ListNode *tail = head;

      while(tail->next != NULL) tail = tail->next;

      return findroot(head, tail);     

   }

Tuesday, April 9, 2013

Construct Binary Tree from Inorder and Postorder Traversal (C++ code)

LeetCode Construct Binary Tree from Inorder and Postorder Traversal, Sep 30 '12
难度3,出现频率3
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.

思路:  postorder的末位元素是root,在inorder中找root,两边分别是左子树和右子树,递归。

 TreeNode *buildTree(vector<int> &inorder, int istart, int iend, vector<int> &postorder, int pstart, int pend){
    if(istart > iend) return NULL;
    TreeNode *root = new TreeNode(postorder[pend]);  
    int i;
    
    for( i = istart; i <= iend; i++){
      if(inorder[i] == root->val) break;
    }
    if(i > iend) return NULL;
    root->left = buildTree(inorder, istart, i -1, postorder, pstart, pstart + i -1 - istart);
    root->right = buildTree(inorder, i + 1, iend, postorder,  pstart + i - istart , pend - 1);
    return root;
  }

  TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        int  n = postorder.size();
        if(n != inorder.size()) return NULL;
        

      return  buildTree(inorder, 0, n-1, postorder, 0, n-1);
       
       
    } 


LeetCode Construct Binary Tree from Preorder and Inorder TraversalSep 30 '12
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.


思路:同上,preorder的第一个元素是root,在inorder中找root,分开左子树和右子树,递归。

TreeNode *buildTree(vector<int> &preorder, int pstart, int pend, vector<int> &inorder, int istart, int iend){
  if(pstart > pend) return NULL;
  TreeNode *root = new TreeNode(preorder[pstart]);
  int i;
  for(i = istart; i <= iend; i++){
   if(inorder[i] == root->val) break;
  }
 if(i > iend) return NULL;
 int temp = pstart + i - istart;
 root->left = buildTree(preorder, pstart + 1, temp , inorder, istart, i - 1);
 root->right = buildTree(preorder, temp + 1, pend, inorder, i + 1, iend);

 return root;
}

 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        if(preorder.size() != inorder.size()) return NULL;
        return buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);    
    }

Monday, April 8, 2013

Binary Tree Zigzag Level Order Traversal (C++ code)

LeetCode Binary Tree Zigzag Level Order Traversal, Sep 29 '12
难度4,出现频率3
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7
return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]
 
思路: 跟level order traversal一致,只是多一个flag记录每层正向还是逆向。

  1. vector<vector<int>> zigzagLevelOrder(TreeNode *root){  
  2.   vector<vector<int>> res;  
  3.   if(!root) return res;   
  4.   vector<int> level;  
  5.   queue<TreeNode *> myque;  
  6.   bool flag = true;   
  7.   TreeNode *last = root;  
  8.   myque.push(root);   
  9.   //main loop  
  10.   while(!myque.empty()){  
  11.    root = myque.front();  
  12.    myque.pop();  
  13.    if(root->left) myque.push(root->left);  
  14.    if(root->right) myque.push(root->right);  
  15.    if(flag == true)level.push_back(root->val);  
  16.    else level.insert(level.begin(), root->val);  
  17.    //when current level ends, store level in result, reset flag and level variable.  
  18.    if(root == last){  
  19.      res.push_back(level);  
  20.      level.clear();  
  21.      last = myque.back();  
  22.      flag = !flag;   
  23.    }   
  24.   }  
  25.   return res;   
  26. }   

Sunday, April 7, 2013

Binary Tree Maximum Path Sum (C++ code)

LeetCode Binary Tree Maximum Path Sum, Nov 8 '12
难度4,出现频率2
  Given a binary tree, find the maximum path sum.The path may start and end at any node in the tree.
For example: Given the below binary tree,
       1
      / \
     2   3
Return 6.
思路: recursion,在当前node, 设定函数返回包含当前node最长单向path,最大和可能是:
1,当前node + 左边最长单向(if >0) +右边最长单向(if >0)
2, 从左边node开始的最大和
3,从右边node开始的最大和
所以函数要返回的是包括当前node的最长单向和,同时在主体里更新最大和。

int maxDirected(TreeNode *root, int &maxSofar){
   if(!root) return 0;   
   int leftmax = maxDirected(root->left, maxSofar);
   int rightmax = maxDirected(root->right, maxSofar);
   int temp = root->val;
   temp = temp + max(leftmax,0) + max(rightmax,0); //temp is the max sum containing root;
   maxSofar = max(maxSofar, temp);

   int directedSum =  max(leftmax, rightmax );
  directedSum = root->val +max(directedSum,0);

   return directedSum ;
}

int maxPathSum(TreeNode *root){
   if(!root) return INT_MIN;
   int maxSofar = root->val ;
  
  maxDirected(root, maxSofar);

  return maxSofar;
}

Binary Tree Level Order Traversal I, II(C++ code)

LeetCode Binary Tree Level Order Traversal,Sep 29 
 难度3,出现频率4
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
].
 
思路: 辅助数据结构queue,每次从头pop一个node, 后面就push node's children.这里要求每层单存一个list,
所以记得用一个指针last记录每层的最后一个node,每当遍历到last时,更新last为当前queue的末尾。
Code如下:

vector<vector<int>> levelOrder(TreeNode *root){
  vector<vector<int>> res;
  if(!root) return res;
  queue<TreeNode *> myque;
  vector<int> level;
  TreeNode *last = root;
  myque.push(root);

  while(!myque.empty()){
     root = myque.front();
     myque.pop();
     level.push_back(root->val);
    if(root->left) myque.push(root->left);
    if(root->right) myque.push(root->right);
    
    if(root == last) {
     last = myque.back();
     res.push_back(level);
     level.clear();
    }
  }
  
  return res;



Binary Tree Level Order Traversal II, Oct 1 '12
难度3,出现频率1
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7
return its bottom-up level order traversal as:

[
  [15,7]
  [9,20],
  [3],
]

思路: 从上题基本一样,只是每个level存进result的时候,是从头存进去。

vector<vector<int>> levelOrder(TreeNode *root){
  vector<vector<int>> res;
  if(!root) return res;
  queue<TreeNode *> myque;
  vector<int> level;
  TreeNode *last = root;
  myque.push(root);

  while(!myque.empty()){
     root = myque.front();
     myque.pop();
     level.push_back(root->val);
    if(root->left) myque.push(root->left);
    if(root->right) myque.push(root->right);
    
    if(root == last) {
     last = myque.back();
     res.insert(res.begin(),level);
     level.clear();
    }
  }
  
  return res;
}

Binary Tree Inorder Traversal(C++ code)

LeetCode Binary Tree Inorder Traversal, Aug 27 '12
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},

先来个recursion的:

void doinorder(TreeNode *root, vector<int> & res){
  if (root == NULL) return;
  doinorder(root->left, res);
  res.push_back(root->val);
  doinorder(root->right, res);


vector<int> inorderTraversal(TreeNode *root){
  vector<int> res; 

  if(root == NULL)  return res;
  
  doinorder(root,  res);
  
  return res;
}

然后是iterative的:

vector<int> inorderTraversal(TreeNode *root){
  vector<int> res; 

  stack<TreeNode *> stk;
  if(root == NULL)  return res;
 
  while(!stk.empty()|| root){
    while(root != NULL) {
       stk.push(root);
       root = root->left;
     }
    root = stk.top();
    stk.pop();
    res.push_back(root->val);
    root = root->right;
   
  }
  
  return res;
}

Further reading:
http://en.wikipedia.org/wiki/Threaded_binary_tree

Wednesday, April 3, 2013

Balanced Binary Tree(C++ code)

LeetCode Balanced Binary TreeOct 9 '12
 难度1,出现频率2
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Tip:
The depth of a node is the number of edges from the node to the tree's root node.
The height of a node is the number of nodes on the longest path from the node to a leaf.


int depth(TreeNode *node){
     if(node == NULL) return 0;
     int maxh;
     maxh = 1 + max(depth(node->left), depth(node->right));
     return maxh;
}


bool isBalanced(TreeNode *node){
     if(node == NULL) return true;
    
     if( abs(depth(node->left) - depth(node->right)) > 1) return false;
     if(isBalanced(node->left) && isBalanced(node->right)) return true;
   
     return false;
}