zoukankan      html  css  js  c++  java
  • leetCode(42):Flatten Binary Tree to Linked List 分类: leetCode 2015-07-17 18:31 96人阅读 评论(0) 收藏

    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

    If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.


    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void flatten(TreeNode* root) {
            if (root == NULL)
        		return;
        	TreeNode* rightNode = root->right;//保存右孩子
        	TreeNode* tmp = root->left;
        	while (tmp && tmp->right)
        	{
        		tmp = tmp->right;
        	}//找到右子的直接前驱
        		
        	if (tmp)//如果左孩子不为空
        	{
        		tmp->right = rightNode;//让直接前驱指向保存的右孩子
        		root->right = root->left;//右指针指向左孩子
        		root->left = NULL;//左指针指向空
        		flatten(root->right);//对左孩子作同样的处理
        	}
        	flatten(rightNode);//对右孩子作同样的处理
        }
    };



  • 相关阅读:
    富文本
    管理员状态
    分页
    tp。3.2中的模板基础
    get和post之间的区别
    RegExp
    获取各种类型的节点
    节点的层次关系
    创建元素节点
    JavaScript 正则
  • 原文地址:https://www.cnblogs.com/zclzqbx/p/4687055.html
Copyright © 2011-2022 走看看